import axios from 'axios';
import { MessageBox, Message } from 'bi-eleme';
import Vue from 'vue';
import store from '@/store';
import { getToken } from '@/utils/auth';

const { CancelToken } = axios;
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});
function cancelPending(config) {
  // 这些接口不取消重复请求
  if (config.url.indexOf('/admin/common/getOssSts') !== -1) {
    // console.log('不取消重复请求', config.url)
    return false;
  }
  store.state.user.axiosCancelList.forEach((item, index) => {
    if (config) {
      const url = config.data ? config.url + JSON.stringify(config.data) : config.url;
      if (item.url == url) {
        item.cancel(`重复请求,已取消之前的请求${url}`);
        store.state.user.axiosCancelList.splice(index, 1);
      }
    } else {
      item.cancel();
      store.state.user.axiosCancelList.splice(index, 1); // 移除当前请求记录
    }
  });
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 每次请求的时候检查是否重复请求
    // cancelPending(config)
    // cancelPending(config)
    // 取消请求
    config.cancelToken = new CancelToken((c) => {
      const axiosCancelList = JSON.parse(JSON.stringify(store.state.user.axiosCancelList));
      axiosCancelList.push({
        url: config.data ? config.url + JSON.stringify(config.data) : config.url,
        cancel: c,
      });
      store.commit('user/set_axiosCancelList', axiosCancelList);
    });

    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.authToken = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    // 拦截相应
    // cancelPending(response.config)

    const res = response.data;
    if (
      res.status_code === 1 ||
      res.status_code === 200 ||
      res.status_code == 41001 ||
      res.status_code == 0 ||
      res.status_code == -101
    ) {
      return res;
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.status_code !== 1) {
      if (res.status_code === -1) {
        if (
          response.config.url.indexOf('/mini_app_playlet/promotionalLinks') != -1 ||
          response.config.url.indexOf('/admin/channel/channelTemplateSav') !== -1 ||
          response.config.url.indexOf('/admin/channel/batchChannelTemplateSave') !== -1
        ) {
          return Promise.reject(res.msg);
        }
        Message({
          message: res.message || res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000,
        });
        return res;
      }
      Message({
        message: res.message || res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status_code === -100 || res.status_code === 50012 || res.status_code === 50014) {
        // to re-login
        MessageBox.confirm('登录过期,请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(new Error(res.message || res.msg || 'Error'));
    }
    return res;
  },
  (error) => {
    if (axios.isCancel(error)) {
      console.log(error);
      return new Promise(() => {});
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

export default service;
